package com.wowangz.cms.topic.poster.tag;

import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import com.wowangz.cms.common.utils.SysConstant;
import com.wowangz.cms.syscore.utils.MessageResourcesUtils;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class FileUploadTag extends TagSupport {
	/**
	 * 
	 */
	private static final long serialVersionUID = 2964791283158040755L;
	private Map<String, Object> model = new HashMap<String, Object>();
	private Integer sortnumber;
	private String dir;
	private Integer type;
	private Long attachmentSize;
	
	public String getDir() {
		return dir;
	}
	
	public void setDir(String dir) {
		this.dir = dir;
	}
	
	public Integer getSortnumber() {
		return sortnumber;
	}
	
	public void setSortnumber(Integer sortnumber) {
		this.sortnumber = sortnumber;
	}
	
	public Integer getType() {
		return type;
	}

	public void setType(Integer type) {
		this.type = type;
	}

	public Long getAttachmentSize() {
		return attachmentSize;
	}
	
	public void setAttachmentSize(Long attachmentSize) {
		this.attachmentSize = attachmentSize;
	}
	
	public Map<String, Object> getModel() {
		return model;
	}

	public void setModel(Map<String, Object> model) {
		this.model = model;
	}

	@Override
	public int doEndTag() throws JspException {
		HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
		String ctx = request.getContextPath();
		this.model.put("ctx", ctx);
		model.put("contentFilter", SysConstant.YesOrNo.NO);
		if (this.sortnumber == null) {
			sortnumber = 0;
		}
		if (this.attachmentSize == null) {
			attachmentSize = 999999999999999999l;
		}
		model.put("dir", dir);
		model.put("attachmentSize", attachmentSize);
		model.put("sortnumber", sortnumber);
		
		model.put("startupload", MessageResourcesUtils.getMessage(request, "topic.attachment.upload.startupload"));
		model.put("selectfile", MessageResourcesUtils.getMessage(request, "topic.attachment.upload.selectfile"));
		try {
			Configuration configuration = new Configuration();
			configuration.setClassForTemplateLoading(FileUploadTag.class, "template");
			Template template = null;
			if (this.type == SysConstant.FileType.IMAGE) {
				template = configuration.getTemplate("fileUpload.ftl", "UTF-8");
			} else {
				template = configuration.getTemplate("otherFileUpload.ftl", "UTF-8");
			}
			StringWriter writer = new StringWriter();
			template.process(this.model, writer);
			this.pageContext.getOut().write(writer.toString());
			
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TemplateException e) {
			e.printStackTrace();
		}
		return EVAL_PAGE;
	}
}
